package com.fangngng.pushall.service.impl;

import com.fangngng.pushall.constant.ErrorCode;
import com.fangngng.pushall.dto.Result;
import com.fangngng.pushall.entity.Role;
import com.fangngng.pushall.entity.User;
import com.fangngng.pushall.entity.UserRole;
import com.fangngng.pushall.exception.BusinessException;
import com.fangngng.pushall.exception.GlobeExceptionAdvice;
import com.fangngng.pushall.mapper.RoleMapper;
import com.fangngng.pushall.mapper.UserMapper;
import com.fangngng.pushall.mapper.UserRoleMapper;
import com.fangngng.pushall.service.LoginService;
import com.fangngng.pushall.util.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * @author:fangn
 * @Date:2020/2/12
 **/
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param email
     * @param password
     * @param validateCode
     * @return
     */
    @Override
    public Result<User> register(String email, String password, String validateCode, String nickName) {
        log.info("注册开始，email:{}, nickName:{}", email, nickName);

        User user = new User();
        user.setName(email);
        user.setLifecycle(User.LIFECYCLE_ENABLE);
        List<User> users = userMapper.select(user);
        if (users != null && !users.isEmpty()) {
            log.warn("注册时， 用户已存在, email:{}", email);
            throw new BusinessException(ErrorCode.ERROR_REGISTER_USER_EXIST);
        }

        //if(!"0556".equals(validateCode)){
        //    log.warn("注册时， 用户验证码不正确， email:{}, validateCode:{}", email, validateCode);
        //    return new Result<String>(ErrorCode.ERROR_REGISTER_VALIDATE_CODE);
        //}

        // 用户不存在， 验证码正确，可以注册
        user.setEmail(email);
        user.setCode(nickName);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(new Date());
        user.setNickName(nickName);
        user.setLifecycle(User.LIFECYCLE_ENABLE);
        user.setCheckStatus(true);
        userMapper.insert(user);

        Role select = new Role();
        select.setName("USER");
        Role roleDb = roleMapper.selectOne(select);
        if (roleDb == null) {
            Role role = new Role();
            role.setName("USER");
            roleMapper.insert(role);
            roleDb = role;
        }
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleDb.getId());
        userRole.setUserId(user.getId());
        userRoleMapper.insert(userRole);

        log.info("用户注册成功, email:{}", email);
        return Result.ok(user);
    }

    /**
     * 登录
     *
     * @param email
     * @param password
     * @return
     */
    @Override
    public Result<String> login(String email, String password) {
        User user = new User();
        user.setName(email);
        List<User> users = userMapper.select(user);
        if (users != null && !users.isEmpty()) {
            log.warn("登录时， 用户不存在, email:{}", email);
            return new Result<String>(ErrorCode.ERROR_LOGIN_USER_NOT_EXIST);
        }

        User userDb = users.get(0);
        if (!userDb.getPassword().equals(password)) {
            log.warn("登录时， 用户密码不正确, email:{}, inputPassword:{}", email, password);
            return new Result<String>(ErrorCode.ERROR_LOGIN_USER_PASSWORD_NOT_CORRECT);
        }

        log.info("登录成功, email:{}", email);

        return Result.ok();
    }

    @Override
    public String getJwtToken(String userName, Boolean isRememberMe) {
        Role select = new Role();
        select.setName("USER");
        Role roleDb = roleMapper.selectOne(select);
        if (roleDb == null) {
            log.warn("用户权限不存在");
            throw new BusinessException(ErrorCode.ERROR_PERMISSION_FORBIT);
        }
        String token = JwtTokenUtils.createToken(userName, roleDb.getName(), isRememberMe);
        log.info("jwt token generated, userName:{}, role:{}, rememberMe:{}, token:{}", userName, roleDb.getName(), isRememberMe, token);
        return token;
    }
}
